package com.zzsz.aspect;

import com.zzsz.annotation.ZzszRecordStockLog;
import com.zzsz.common.core.domain.model.LoginUser;
import com.zzsz.common.utils.SecurityUtils;
import com.zzsz.domain.ZzszAddProductsDTO;
import com.zzsz.domain.ZzszStockOperationLog;
import com.zzsz.mapper.StockLogMapper;
import com.zzsz.service.impl.InventoryServiceImpl;
import com.zzsz.service.impl.StockLogServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.sql.Date;

/**
 * @Classname StockLogAspect
 * @Description
 * @Date 2025/9/3 21:42
 * @Created by SYL
 */

@Aspect
@Component
@Slf4j
public class StockLogAspect {
    @Autowired
    private InventoryServiceImpl inventoryService;

    @Autowired
    private StockLogServiceImpl stockLogService;

    @Autowired
    private StockLogMapper stockLogMapper;

    // 定义切点
    @Pointcut("@annotation(recordStockLog)")
    public void stockOperationPointcut(ZzszRecordStockLog recordStockLog) {
    }
    // 后置增强：方法执行成功后记录日志
    @AfterReturning(pointcut = "@annotation(recordStockLog)", returning = "result")
    public void afterReturning(JoinPoint joinPoint, ZzszRecordStockLog recordStockLog, Object result) {
        handleLog(joinPoint, recordStockLog, result, null);
    }

    // 异常通知：方法执行异常时记录日志
    @AfterThrowing(pointcut = "@annotation(recordStockLog)", throwing = "e")
    public void afterThrowing(JoinPoint joinPoint, ZzszRecordStockLog recordStockLog, Exception e) {
        handleLog(joinPoint, recordStockLog, null, e);
    }


    protected void handleLog(final JoinPoint joinPoint, ZzszRecordStockLog recordStockLog, Object result, Exception e) {

        try {
            // 1. 获取方法参数
            Object[] args = joinPoint.getArgs();

            // 2. 解析出关键参数
            ZzszAddProductsDTO addProductsDTO = null;
            Integer count = null;


            for (Object arg : args) {
                if (arg instanceof ZzszAddProductsDTO) {
                    addProductsDTO = (ZzszAddProductsDTO) arg;
                    if (addProductsDTO != null) {
                        count = addProductsDTO.getQuantity();
                    }
                    break;
                }
            }

            log.info("切面类记录日志,{}"+addProductsDTO);

            // 3. 获取当前用户信息
            String operator = "未知用户";
            try {
                LoginUser loginUser = SecurityUtils.getLoginUser();
                if (loginUser != null && loginUser.getUser() != null) {
                    operator = loginUser.getUser().getUserName();
                }
            } catch (Exception ex) {
                log.warn("无法获取当前用户信息: {}", ex.getMessage());
            }
            // 4. 构建日志对象
            ZzszStockOperationLog logEntity = new ZzszStockOperationLog();
            // 填充日志信息
            if (recordStockLog != null) {
                logEntity.setOperationType(recordStockLog.value().name());
                logEntity.setDescription(recordStockLog.desc());
            }
            // 从DTO中获取商品信息
            // productId需要从方法返回结果中获取，因为DTO主要用于接收参数
            if (result instanceof Long) {
                Long productId = (Long) result;
                logEntity.setProductId(productId);
            }
            logEntity.setCount(Long.valueOf(count != null ? count : 0));
            logEntity.setOperator(operator);
            logEntity.setOperateTime(new Date(System.currentTimeMillis()));
            // 设置状态和错误信息
            if (e != null) {
                logEntity.setStatus("FAILED");
                String errorMsg = e.getMessage();
                if (errorMsg != null) {
                    if (errorMsg.length() > 200) {
                        errorMsg = errorMsg.substring(0, 200);
                    }
                } else {
                    errorMsg = "未知错误";
                }
                logEntity.setErrorMsg(errorMsg);
            } else {
                logEntity.setStatus("SUCCESS");
            }
            // 5. 记录日志
            if (stockLogMapper != null) {
                if (e != null) {
                    // 失败时使用saveLog方法
                    //stockLogMapper.saveLog(logEntity);
                    System.out.println("切面类记录是失败日志");
                } else {
                    // 成功时使用insert方法
                    stockLogMapper.insert(logEntity);
                }
            }
        } catch (Exception ex) {
            log.error("处理日志记录时发生异常: ", ex);
        }

    }


}
